<template>
  <el-dialog
    v-model="showDialog"
    :title="title"
    :append-to-body="true"
    :width="width"
    @closed="closeDialog"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <super-form
      :formAndTable="false"
      ref="pointDialogRef"
      v-bind="formOption"
      :modelValue="formData"
      :rules="formRules"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog(false)"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click.stop="handleSubmit" @keyup.enter="keyDown">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, useTemplateRef } from "vue";
import { type FormRules } from "element-plus";
import SuperForm from "@/components/SuperForm/index.vue";
import { FormOption } from "@/components/SuperForm/formType";
import { FormPoint } from "./formConfig";
interface Props {
  width?: number; // 宽度
  title?: string; // 标题
  type: string; // 类型
}
const { width = 600, title, type } = defineProps<Props>();
const emits = defineEmits<{
  handleSubmit: [_row: any];
  handleClose: any;
}>();

// 弹窗
const showDialog = ref<boolean>(false);
const loading = ref<boolean>(false);
// 表单ref实例
const pointDialogRef = useTemplateRef<any>("pointDialogRef");
// 表单
const formData = ref<any>({});
const formOption = ref<FormOption>({formItems: []});
const formRules = ref<FormRules>({});

// 关闭
const closeDialog = (isClose?: boolean | undefined): void => {
  pointDialogRef.value?.ruleFormRef?.resetFields();
  showDialog.value = false;
  loading.value = false;
  formData.value = {};
  emits("handleClose", isClose);
  window.removeEventListener("keydown", keyDown, false);
};
// 打开
const openDialog = (data: any = {}): void => {
  const formPoint = new FormPoint();
  formRules.value = formPoint.formRules;
  formOption.value = formPoint.formOption;
  Object.assign(formData.value, formPoint.formData, { ...data });
  showDialog.value = true;
  loading.value = false;
  nextTick(() => {
    window.addEventListener("keydown", keyDown);
  });
};
// 表单提交
const handleSubmit = (): void => {
  pointDialogRef.value.ruleFormRef.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const params = {
        station_name: formData.value.station_name,
        category: formData.value.category,
      };
      console.log(params, "表单提交");
      if (type === "edit") {
        ElMessage.success("编辑成功");
        closeDialog(true);
      } else {
        ElMessage.success("新增成功");
        closeDialog(true);
      }
    }
  });
};
// 键盘事件
const keyDown = (e: any) => {
  if (e.keyCode === 13) {
    handleSubmit();
  }
};
defineExpose({
  closeDialog,
  openDialog,
});
</script>
